<?php
/*
+-----------------------------------------------------------------------------+
| $Id: footer.php,v 2.00 2005/01/15 05:02:00 Bleakwind Exp $
| The function.php
| Copyright (c) 2003-2004 Weaverdream
| http://www.weaverdream.com
+-----------------------------------------------------------------------------+
*/

// Return file data
function read_file($filename, $mode="rb")
{
   $handle = fopen($filename, $mode);
   flock($handle, LOCK_EX);
   $data = fread($handle, filesize($filename));
   fclose($handle);
   return $data;
}

// Put the data into file
function write_file($filename, $data, $mode="rb+")
{
   touch($filename);
   $handle = fopen($filename, $mode);
   flock($handle, LOCK_EX);
   $fettle = fwrite($handle, $data);
   if($mode == "rb+") {ftruncate($handle, strlen($data));}
   fclose($handle);
   return $fettle;
}

// Return visitor's IP
function return_ip()
{
   if(!empty($_SERVER['HTTP_CLIENT_IP'])) {
       $ip = $_SERVER['HTTP_CLIENT_IP'];
   } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
       $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
   } elseif (!empty($_SERVER['REMOTE_ADDR'])) {
       $ip = $_SERVER['REMOTE_ADDR'];
   } else {
       $ip = "Unknown";
   }
   return trim($ip);
}

// Return visitor's OS
function return_os()
{
   $agent = $_SERVER["HTTP_USER_AGENT"];

   if(preg_match('/Win/i', $agent) && preg_match('/NT 5.2/i', $agent)) {// Windows 2003
       $os = "Win2003";
   } elseif (preg_match('/Win/i', $agent) && preg_match('/NT 5.1/i', $agent)) {// Windows XP
       $os = "WinXP";
   } elseif (preg_match('/Win/i', $agent) && preg_match('/NT 5.0/i', $agent)) {// Windows 2000
       $os = "Win2000";
   } elseif (preg_match('/Win/i', $agent) && preg_match('/NT/i', $agent)) {// Windows NT
       $os = "Win2000";
   } elseif (preg_match('/Win/i', $agent) && preg_match('/4.90/i', $agent)) {// Windows ME
       $os = "Win9X";
   } elseif (preg_match('/Win/i', $agent) && preg_match('/98/i', $agent)) {// Windows 98
       $os = "Win9X";
   } elseif (preg_match('/Win/i', $agent) && preg_match('/95/i', $agent)) {// Windows 95
       $os = "Win9X";
   } elseif (preg_match('/Win/i', $agent) && preg_match('/32/i', $agent)) {// Windows 32
       $os = "Win9X";
   } elseif (preg_match('/Linux/i', $agent)) {// linux
       $os = "Linux";
   } elseif (preg_match('/BSD/i', $agent)) {// *BSD
       $os = "Unix";
   } elseif (preg_match('/Unix/i', $agent)) {// Unix
       $os = "Unix";
   } elseif (preg_match('/Sun/i', $agent)) {// SunOS
       $os = "SunOS";
   } elseif (preg_match('/Mac/i', $agent)) {// Macintosh
       $os = "Macintosh";
   } elseif (preg_match('/IBM/i', $agent)) {// IBMOS
       $os = "IBMOS";
   } else {// Other
       $os = "Other";
   }

   return trim($os);
}

// Return visitor's browser
function return_browser()
{
   $agent = $_SERVER["HTTP_USER_AGENT"];

   if(preg_match('/Firefox/i',$agent)) {
       $browser="Firefox";
   } elseif (preg_match('/Netscape/i',$agent)) {
       $browser="Netscape";
   } elseif (preg_match('/NetCaptor/i',$agent)) {// has MSIE
       $browser="NetCaptor";
   } elseif (preg_match('/MSN/i',$agent)) {// has MSIE
       $browser="MSN Explorer";
   } elseif (preg_match('/Opera/i',$agent)) {// has MSIE
       $browser="Opera";
   } elseif (preg_match('/AOL/i',$agent)) {
       $browser="AOL";
   } elseif (preg_match('/JAVA/i',$agent)) {
       $browser="JAVA";
   } elseif (preg_match('/MacWeb/i',$agent)) {
       $browser="MacWeb";
   } elseif (preg_match("/MSIE/i", $agent)) {
       $str = explode(";",$agent);
       $str = $str['1'];
       $str = explode(" ",$str);
       $browser_ver = $str['2'];
       if($browser_ver == "6.0") {
           $browser = "IE6";
       } else {
           $browser = "IE5";
       }
   } else {
       $browser = "Other";
   }

   return trim($browser);
}

// Return the the search
function return_search($referrer)
{
   global $SEARCHLIST,$LANGUAGE;
   
   $search  = array();
   $quondam = array("/",".","?");
   $current = array("\/","\.","\?");

   reset($SEARCHLIST);
   while (list($key1, $value1) = each ($SEARCHLIST)) {
       while (list($key2, $value2) = each ($value1['search'])) {
               $pattern = str_replace($quondam,$current,$value2[0]);
               if(preg_match( "/^".$pattern."/i", $referrer)) {
                   preg_match("/".$value2[1]."([^".$value2[2]."]+)/i", $referrer, $matches);
                   $search['name']    = trim($key1);
                   $search['keyword'] = iconv($value2[3], $LANGUAGE['charset'], trim(urldecode($matches[1])));
                   break;
               }
       }
   }

   return $search;
}

// Formatted the time difference from time to now
function time_margin($time, $now, $multiple)
{
   $margin = trim($now) - trim($time);
   $number = ceil($margin/$multiple);
   return $number;
}

// Read dir to list
function return_dir($directory)
{
   $file_list = array();
   if ($handle = opendir($directory)) {
       while (false !== ($file = readdir($handle))) {
           if(($file != ".")&&($file != "..")) {
               $file_list[] = $file;
           }
       }
       closedir($handle);
   }
   sort($file_list);
   return $file_list;
}

// Encrypt the string
function str_encrypt($str,$len = 40)
{
  $encrypt = "";
  $str     = sha1($str);
  $str     = substr($str, 0, 10).substr($str, -10);
  $str     = sha1($str);
  for($i=0;$i<$len;$i++){
      $encrypt .= $str{$i%40};
  }
  return $encrypt;
}

// Resize a image
function resize_image($filename, $width, $height="")
{
   
   $extend_name = substr($filename,-3);
   
   if($extend_name == "png") {
       $str_createfrom = "imagecreatefrompng";
   } elseif ($extend_name == "jpg") {
       $str_createfrom = "imagecreatefromjpeg";
   } elseif ($extend_name == "gif") {
       $str_createfrom = "imagecreatefromgif";
   } elseif ($extend_name == "bmp") {
       $str_createfrom = "imagecreatefromwbmp";
   }

   list($width_get, $height_get, $type_get, $attr_get) = getimagesize($filename);
   if(empty($height)) { $height = (int)(($width / $width_get) * $height_get); }

   $img        = imagecreatetruecolor($width, $height);
   $image_from = $str_createfrom($filename);
   imagecopyresampled($img, $image_from, 0, 0, 0, 0, $width, $height, $width_get, $height_get);

   return $img;
}

// Return a 16 color to a 10 color
function color_hexdec($color)
{
   if(!preg_match("/^[0-9a-z]{6,6}$/i",$color)) { $color = "000000"; }
   $color_array['0'] = hexdec(substr($color,0,2));
   $color_array['1'] = hexdec(substr($color,2,2));
   $color_array['2'] = hexdec(substr($color,4,2));
   return $color_array;
}

// String intercept By Bleakwind At http://www.weaverdream.com
// utf-8:$byte=3 | gb2312:$byte=2 | big5:$byte=2
function bite_str($string, $start, $len, $byte=3)
{
    $str     = "";
    $count   = 1;
    $str_len = strlen($string);
    for ($i=0; $i<$str_len; $i++) {
        if (($count+1-$start)>$len) {
            $str  .= "...";
            break;
        } elseif ((ord(substr($string,$i,1)) <= 128) && ($count < $start)) {
            $count++;
        } elseif ((ord(substr($string,$i,1)) > 128) && ($count < $start)) {
            $count = $count+2;
            $i     = $i+$byte-1;
        } elseif ((ord(substr($string,$i,1)) <= 128) && ($count >= $start)) {
            $str  .= substr($string,$i,1);
            $count++;
        } elseif ((ord(substr($string,$i,1)) > 128) && ($count >= $start)) {
            $str  .= substr($string,$i,$byte);
            $count = $count+2;
            $i     = $i+$byte-1;
        }
    }
    return $str;
}

// Encode a string
function str_encode($str)
{
   if(get_magic_quotes_gpc()) {
       $str = stripslashes($str);
   }

   $str = str_replace("&","&amp;",$str);
   $str = str_replace("\"","&quot;",$str);
   $str = str_replace("'","&#39;",$str);
   $str = str_replace("<","&lt;",$str);
   $str = str_replace(">","&gt;",$str);

   $str = str_replace("|","&#124;",$str);
   $str = str_replace(".","&#46;",$str);

   $str = str_replace("\r","",$str);
   $str = str_replace("\n","<br>",$str);
   $str = str_replace(" ","&nbsp;",$str);

   $str = str_replace("\\","&#92;",$str);

   return $str;
}

// Decode a string
function str_decode($str)
{
   $str = str_replace("&amp;","&",$str);
   $str = str_replace("&quot;","\"",$str);
   $str = str_replace("&#39;","'",$str);
   $str = str_replace("&lt;","<",$str);
   $str = str_replace("&gt;",">",$str);

   $str = str_replace("&#124;","|",$str);
   $str = str_replace("&#46;",".",$str);

   $str = str_replace("<br>","\n",$str);
   $str = str_replace("&nbsp;"," ",$str);

   $str = str_replace("&#92;","\\",$str);

   return $str;
}

// Decode a string
function str_decode_str($str)
{
   $str = str_replace("&amp;","&",$str);
   $str = str_replace("&quot;","\"",$str);
   $str = str_replace("&#39;","'",$str);

   $str = str_replace("&#124;","|",$str);
   $str = str_replace("&#46;",".",$str);

   $str = str_replace("<br>","\n",$str);
   $str = str_replace("&nbsp;"," ",$str);

   $str = str_replace("&#92;","\\",$str);

   return $str;
}

// Decode a string for title
function str_decode_title($str)
{
   $str = str_replace("<br>","",$str);

   return $str;
}

// Check username
function check_username($str)
{
   global $LANGUAGE;
   if(!preg_match("/^[0-9a-z_]{3,60}$/",$str)) {
       header("location:prompt.php?act=failed&mes=".htmlentities(urlencode($LANGUAGE['warning_username'])));
       exit;
   } else {
       return $str;
   }
}

// Check password
function check_password($str)
{
   global $LANGUAGE;
   if(!preg_match("/^[0-9a-z_]{3,60}$/i",$str)) {
       header("location:prompt.php?act=failed&mes=".htmlentities(urlencode($LANGUAGE['warning_password'])));
       exit;
   } else {
       return $str;
   }
}

// Invert IP to address
function invert_ip($ip)
{
   global $SETTING;

   $ip_part    = explode(".",trim($ip));
   $ip_part[0] = sprintf("%03d", $ip_part[0]);

   $file_list  = array();
   if ($handle = opendir($SETTING['dir_ipdata'])) {
       while (false !== ($filename = readdir($handle))) {
           $filename_part = explode(".",$filename);
           if(trim($filename_part[0]) == trim($ip_part[0])) {
               $file_list[] = $filename;
           }
       }
       closedir($handle);
   }

   for($i=0; $i<count($file_list); $i++) {
       $place = search_ip($ip,$SETTING['dir_ipdata'].$file_list[$i]);
       if( $place != "Unknown" && $place != "") { break; }
   }

   return  $place;
}

// Search IP to address
function search_ip($ip,$db)
{
   global $SETTING;

   $ip_part = explode(".",trim($ip));
   for($i=0; $i<4; $i++) { $ip_part[$i] = sprintf("%03d", $ip_part[$i]); }
   $ip      = join(".",$ip_part);

   $file_list = file($db);
   $number    = count($file_list);

   if($number>=10) {
       $part  = floor($number/10); $group = 10;
   } else {
       $part  = $number; $group = 1;
   }

   for($i=0;$i<$group;$i++) {
       $record_begin = $part*$i;
       $record_end   = ($i == $group-1) ? $number-1 : $part*($i+1)-1;
       $ipbegin_part = explode(".",$file_list[$record_begin]);
       $ipend_part   = explode(".",$file_list[$record_end]);
       if( ($ip_part[1] >= $ipbegin_part[1]) && ($ip_part[1] <= $ipend_part[4]) ) {
           for($j = $record_begin;$j <= $record_end;$j++) {
               $file_list_part = explode($SETTING['division1'],$file_list[$j]);
               if(strcmp($ip,$file_list_part[0])>=0 && strcmp($ip,$file_list_part[1])<=0 ) {
                   $place = trim($file_list_part['2']).trim($file_list_part['3']);
                   break;
               }
           }
           break;
       }
   }

   $place = (!empty($place)) ? $place : "Unknown";

   return  $place;
}

// Forbid the IP
function forbid_ip()
{
   global $SETTING;

   $ifhave    = "n";
   $ip        = return_ip();
   $ip_part   = explode(".",$ip);
   $file_list = file($SETTING['file_forbidip']);

   for ($i=1; $i<count($file_list); $i++) {
       $file_list_part = explode(".",$file_list[$i]);
       for($h=0; $h<4; $h++) {
           if((trim($file_list_part[$h]) != trim($ip_part[$h])) && (trim($file_list_part[$h]) != "*")) {
               break;
           } elseif ($h == 3) {
               $ifhave = "y";
               break 2;
           }
       }
   }
   return $ifhave;
}

// Nether is some check function
// Check if visitor can view user
function check_ifview()
{
   global $_GET,$SETTING,$LANGUAGE;

   if(isset($_GET['user']) && ($_GET['user'] != "")) {
       $user        = check_username($_GET['user']);
       $file_config = $SETTING['dir_data'].$user."/".$SETTING['file_config'];
       if(!file_exists($file_config)) {
           header("location:login.php?act=select&mes=".htmlentities(urlencode($LANGUAGE['warning_nouser'])));
           exit;
       } else {
           $_SESSION['sess_select'] = $user;
       }
   } elseif (!isset($_SESSION['sess_select']) || $_SESSION['sess_select'] == "") {
       header("location:login.php?act=select&mes=".htmlentities(urlencode($LANGUAGE['function_selectuser'])));
       exit;
   }
   $file_config = $SETTING['dir_data'].$_SESSION['sess_select']."/".$SETTING['file_config'];
   include $file_config;

   if((CONFIG_IFVIEW == "n") && ($_SESSION['sess_username'] != $_SESSION['sess_select']) && (if_adminlogin() != "y")) {
       header("location:login.php?act=login&mes=".htmlentities(urlencode($LANGUAGE['function_mustlogin'])));
       exit;
   } elseif (($CONFIGUSER['ifview'] == "n") && ($_SESSION['sess_username'] != $_SESSION['sess_select']) && (if_adminlogin() != "y")) {
       header("location:login.php?act=login&mes=".htmlentities(urlencode($LANGUAGE['function_usermustlogin'])));
       exit;
   }

   return TRUE;
}

// Check if select user
function if_selectuser()
{
   $if = "n";
   if(isset($_SESSION['sess_select']) && ($_SESSION['sess_select'] != "")) {
       $if = "y";
   }
   return $if;
}

// Check user login
function check_userlogin()
{
   if(!isset($_SESSION['sess_username']) || ($_SESSION['sess_username'] == "") || !isset($_SESSION['sess_password']) || ($_SESSION['sess_password'] == "")) {
       header("location:login.php?act=login");
       exit;
   } else {
       return TRUE;
   }
}

// Check if user login
function if_userlogin()
{
   $if = "n";
   if(isset($_SESSION['sess_username']) && ($_SESSION['sess_username'] != "") && isset($_SESSION['sess_password']) && ($_SESSION['sess_password'] != "")) {
       $if = "y";
   }
   return $if;
}

// Check admin login
function check_adminlogin()
{
   if(!isset($_SESSION['sess_adminuser']) || ($_SESSION['sess_adminuser'] == "") || !isset($_SESSION['sess_adminpass']) || ($_SESSION['sess_adminpass'] == "")) {
       header("location:admin_login.php?act=login");
       exit;
   } else {
       return TRUE;
   }
}

// Check admin login
function if_adminlogin()
{
   $if = "n";
   if(isset($_SESSION['sess_adminuser']) && ($_SESSION['sess_adminuser'] != "") && isset($_SESSION['sess_adminpass']) && ($_SESSION['sess_adminpass'] != "")) {
       $if = "y";
   }
   return $if;
}
//////

// Sort a planar array into order
function cmp($a, $b)
{
   if($a['key'] == $b['key']) {
       return 0;
   }else{
       return ($a['key'] < $b['key']) ? -1 : 1;
   }
}

// Sort a planar array into reversed order
function rcmp($a, $b)
{
   if($a['key'] == $b['key']) {
       return 0;
   }else{
       return ($a['key'] < $b['key']) ? 1 : -1;
   }
}

// join some str to a array
function join_str($begin,$end,$fill=0)
{
   $str       = array();
   for($i=$begin; $i<=$end; $i++) {
       $str[] = sprintf("%0".$fill."d", $i);
   }
   return $str;
}

// join date to a array
function join_date($sort,$year,$month,$day,$hour)
{
   global $SETTING;

   $array = array();
   if($sort == "hour") {
      for($i=23;$i>=0;$i--) {
         $array[] .= date("YmdH", mktime ($hour-$i,0,0,$month,$day,$year));
      }
   } elseif ($sort == "day") {
      for($i=30;$i>=0;$i--) {
         $array[] .= date("Ymd", mktime ($hour,0,0,$month,$day-$i,$year));
      }
   } elseif ($sort == "month") {
      for($i=11;$i>=0;$i--) {
         $array[] .= date("Ym", mktime ($hour,0,0,$month-$i,$day,$year));
      }
   } elseif ($sort == "year") {
      for($i=$SETTING['howyear']-1;$i>=0;$i--) {
         $array[] .= date("Y", mktime ($hour,0,0,$month,$day,$year-$i));
      }
   }
   return $array;
}

// If have a same IP in period of time
function if_ipsame($filename,$now,$long)
{
   global $SETTING;

   $str = "<?php exit(\"".$SETTING['cannotview']."\");?>\n";
   if(!file_exists($filename)) { write_file($filename,$str); }

   $ip       = return_ip();
   $ifhave   = "n";
   $str_file = "";
   $str_now  = $now.$SETTING['division1'].$ip."\n";
   $file_list = file($filename);
   for($i=1;$i<count($file_list);$i++) {
       $file_list_part = explode($SETTING['division1'],$file_list[$i]);
       $time_margin = trim($now)-trim($file_list_part['0']);
       if( $time_margin < (int)$long ) {
           $str_file .= trim($file_list[$i])."\n";
           if( trim($ip) == trim($file_list_part['1']) ) {
               $ifhave = "y";
           }
       }
   }
   if($ifhave == "y") {
       $str = $str.$str_file;
   }else{
       $str = $str.$str_now.$str_file;
   }
   $fettle = write_file($filename,$str);
   return $ifhave;
}

// Some write function
// Write data to file of click
function write_click($filename,$keyword,$if_ipsame,$length)
{
   global $SETTING;

   $str = "<?php exit(\"".$SETTING['cannotview']."\");?>\n";
   if(!file_exists($filename)) { write_file($filename,$str); }

   $file_list = file($filename);
   for($i=0;$i<count($keyword);$i++) {
       for($j=0;$j<count($file_list);$j++) { // $i must be 1
           $file_list_part = explode($SETTING['division1'],$file_list[$j]);
           if(trim($keyword[$i]) == trim($file_list_part[0])) {
               $ip[$i] = ($if_ipsame == "n") ? ($file_list_part[1]+1) : ($file_list_part[1]+0);
               $pv[$i] = $file_list_part[2]+1;
               if(strlen($ip[$i])>(int)$length) { $ip[$i] = 0; }// initialize IP
               if(strlen($pv[$i])>(int)$length) { $pv[$i] = 0; }// initialize PV
               break;
           } elseif ($j == (count($file_list)-1)) {
               $ip[$i] = "1";
               $pv[$i] = "1";
               break;
           }
       }
       $str .= $keyword[$i].$SETTING['division1'].$ip[$i].$SETTING['division1'].$pv[$i]."\n";
   }
   $fettle = write_file($filename,$str);
   return $fettle;
}

// Period of time of total
function write_totalevery($filename,$keyword,$now,$if_ipsame)
{
   global $SETTING;

   $str = "<?php exit(\"".$SETTING['cannotview']."\");?>\n";
   if(!file_exists($filename)) { write_file($filename,$str); }

   $file_list = file($filename);
   for($i=0;$i<count($keyword);$i++) {
       for($j=0;$j<count($file_list);$j++) {
           $file_list_part = explode($SETTING['division1'],$file_list[$j]);
           if(trim($keyword[$i]) == trim($file_list_part[0])) {
               if(trim($keyword[$i]) == trim($now)) {
                   $ip[$i] = (($if_ipsame == "n") ? ($file_list_part[1]+1) : ($file_list_part[1]+0));
                   $pv[$i] = $file_list_part[2]+1;
                   break;
               }else{
                   $ip[$i] = $file_list_part[1]+0;
                   $pv[$i] = $file_list_part[2]+0;
                   break;
               }
           } elseif ($j == (count($file_list)-1)) {
               $ip[$i] = (trim($keyword[$i]) == trim($now)) ? "1" : "0";
               $pv[$i] = (trim($keyword[$i]) == trim($now)) ? "1" : "0";
               break;
           }
       }
       $str .= $keyword[$i].$SETTING['division1'].$ip[$i].$SETTING['division1'].$pv[$i]."\n";
   }
   $fettle = write_file($filename,$str);
   return $fettle;
}

// Period of time of latest time
function write_lastevery($filename,$keyword,$if_ipsame)
{
   global $SETTING;

   $str = "<?php exit(\"".$SETTING['cannotview']."\");?>\n";
   if(!file_exists($filename)) { write_file($filename,$str); }

   $num_keyword     = count($keyword);
   $file_list       = file($filename);
   $num_file_list   = count($file_list);

   for($i=0;$i<$num_keyword;$i++) {
       for($j=0;$j<$num_file_list;$j++) {
           $file_list_part = explode($SETTING['division1'],$file_list[$j]);
           if(trim($keyword[$i]) == trim($file_list_part[0])) {
               if($i==($num_keyword-1)) {
                   $ip[$i] = (($if_ipsame == "n") ? ($file_list_part[1]+1) : ($file_list_part[1]+0));
                   $pv[$i] = $file_list_part[2]+1;
                   break;
               }else{
                   $ip[$i] = $file_list_part[1]+0;
                   $pv[$i] = $file_list_part[2]+0;
                   break;
               }
           } elseif ($j == ($num_file_list-1)) {
               $ip[$i] = ($i==($num_keyword-1)) ? "1" : "0";
               $pv[$i] = ($i==($num_keyword-1)) ? "1" : "0";
               break;
           }
       }
       $str .= $keyword[$i].$SETTING['division1'].$ip[$i].$SETTING['division1'].$pv[$i]."\n";
   }
   $fettle = write_file($filename,$str);
   return $fettle;
}

// Every of total
function write_every_add($filename,$this,$now,$number,$long,$if_ipsame)
{
   global $SETTING;

   $str = "<?php exit(\"".$SETTING['cannotview']."\");?>\n";
   if(!file_exists($filename)) { write_file($filename,$str); }

   $ifhave = "n";
   $str_array = array();
   $file_list = file($filename);
   for($i=0;$i<count($file_list);$i++) {
       $file_list_part = explode($SETTING['division1'],$file_list[$i]);
       if( count($file_list_part) == 4 && trim(strtolower($this)) == trim(strtolower($file_list_part[0])) ) {
           $ifhave = "y";
           $keyword[$i] = trim($file_list_part[0]);
           $ip[$i]      = ($if_ipsame == "n") ? ($file_list_part[1]+1) : ($file_list_part[1]+0);
           $pv[$i]      = $file_list_part[2]+1;
           $time[$i]    = $now;
           $str_array[] = array("key" => $ip[$i],$keyword[$i],$ip[$i],$pv[$i],$time[$i]);
       } elseif (count($file_list_part) == 4) {
           $keyword[$i] = trim($file_list_part[0]);
           $ip[$i]      = $file_list_part[1]+0;
           $pv[$i]      = $file_list_part[2]+0;
           $time[$i]    = $file_list_part[3];
           $str_array[] = array("key" => $ip[$i],$keyword[$i],$ip[$i],$pv[$i],$time[$i]);
       }
       if( ($i == (count($file_list)-1)) && ($ifhave == "n") ) {
           $keyword[$i] = trim($this);
           $ip[$i]      = "1";
           $pv[$i]      = "1";
           $time[$i]    = $now;
           $str_array[] = array("key" => $ip[$i],$keyword[$i],$ip[$i],$pv[$i],$time[$i]);
       }
   }

   usort($str_array, "rcmp");
   reset($str_array);
   $i=1;
   while(list ($key, $value) = each ($str_array)) {
      $str .= $value[0]."|".$value[1]."|".$value[2]."|".$value[3]."\n";
      $i++;
      if($i > $number && ($now-$value[3]) > $long){ break; }
   }

   $fettle = write_file($filename,$str);
   return $fettle;
}

// Online visitor
function write_online($filename,$long,$time,$href,$referrer)
{
   global $SETTING;

   $str = "<?php exit(\"".$SETTING['cannotview']."\");?>\n";
   if(!file_exists($filename)) { write_file($filename,$str); }

   $href     = str_encode($href);
   $referrer = str_encode($referrer);
   $ip       = return_ip();
   $place    = invert_ip($ip);
   $str     .= trim($time).$SETTING['division1'].trim($ip).$SETTING['division1'].trim($place).$SETTING['division1'].trim($href).$SETTING['division1'].trim($referrer)."\n";
   $file_list = file($filename);
   for($i=1;$i<count($file_list);$i++) {
       $file_list_part = explode($SETTING['division1'],$file_list[$i]);
       $time_margin    = trim($time) - trim($file_list_part['0']);
       if( ($time_margin < (int)$long) && (trim($ip) != trim($file_list_part['1'])) ) {
           $str .= trim($file_list[$i])."\n";
       }
   }
   $fettle = write_file($filename,$str);
   return $fettle;
}

// Last visitor
function write_visitor($filename,$number,$time,$href,$referrer)
{
   global $SETTING;

   $str = "<?php exit(\"".$SETTING['cannotview']."\");?>\n";
   if(!file_exists($filename)) { write_file($filename,$str); }

   $href     = str_encode($href);
   $referrer = str_encode($referrer);

   $ip    = return_ip();
   $place = invert_ip($ip);
   $str  .= trim($time).$SETTING['division1'].trim($ip).$SETTING['division1'].trim($place).$SETTING['division1'].trim($href).$SETTING['division1'].trim($referrer)."\n";
   $file_list = file($filename);
   for($i=1;$i<count($file_list);$i++) {
       if($i < $number) {
           $str .= trim($file_list[$i])."\n";
       }else{
           break;
       }
   }
   $fettle = write_file($filename,$str);
   return $fettle;
}
//////

////// Some readfile function
// Read  file of click.php to array
function read_click($filename,$keyword)
{
   global $SETTING;

   $str = "<?php exit(\"".$SETTING['cannotview']."\");?>\n";
   if(!file_exists($filename)) { write_file($filename,$str); }

   $data      = array();
   $file_list = file($filename);
   for($i=0;$i<count($keyword);$i++) {
       for($j=1;$j<count($file_list);$j++) {
           $file_list_part = explode($SETTING['division1'],$file_list[$j]);
           if(trim($keyword[$i]) == trim($file_list_part[0])) {
               $data['ip'][$i] = (int)trim($file_list_part[1]);
               $data['pv'][$i] = (int)trim($file_list_part[2]);
               break;
           } elseif ($j == (count($file_list)-1)) {
               $data['ip'][$i] = "0";
               $data['pv'][$i] = "0";
               break;
           }
       }
   }
   return $data;
}

// Read file of visitor.php to array
function read_visitor($filename)
{
   global $SETTING;

   $str = "<?php exit(\"".$SETTING['cannotview']."\");?>\n";
   if(!file_exists($filename)) { write_file($filename,$str); }

   $data = array();
   $file_list = file($filename);
   for($i=1;$i<count($file_list);$i++) {
       $file_list_part = explode($SETTING['division1'],$file_list[$i]);
       $data['time'][$i]     = trim($file_list_part[0]);
       $data['ip'][$i]       = trim($file_list_part[1]);
       $data['place'][$i]    = trim($file_list_part[2]);
       $data['href'][$i]     = trim(str_decode_str($file_list_part[3]));
       $data['referrer'][$i] = trim(str_decode_str($file_list_part[4]));
   }
   return $data;
}

// Read file of online.php to array
function read_online($filename,$long,$time)
{
   global $SETTING;

   $str = "<?php exit(\"".$SETTING['cannotview']."\");?>\n";
   if(!file_exists($filename)) { write_file($filename,$str); }

   $data           = array();
   $data['number'] = 0;
   $file_list = file($filename);
   for($i=1;$i<count($file_list);$i++) {
       $file_list_part = explode($SETTING['division1'],$file_list[$i]);
       $time_margin    = trim($time)-trim($file_list_part['0']);
       if( $time_margin < (int)$long ) {
           $data['time'][$i]     = trim($file_list_part[0]);
           $data['ip'][$i]       = trim($file_list_part[1]);
           $data['place'][$i]    = trim($file_list_part[2]);
           $data['href'][$i]     = trim(str_decode_str($file_list_part[3]));
           $data['referrer'][$i] = trim(str_decode_str($file_list_part[4]));
           $data['number']++;
           $str .= trim($file_list[$i])."\n";
       }
   }
   $fettle = write_file($filename,$str);
   return $data;
}

// Read the data to array
function read_list($filename,$keyword)
{
   global $SETTING;

   $str = "<?php exit(\"".$SETTING['cannotview']."\");?>\n";
   if(!file_exists($filename)) { write_file($filename,$str); }

   $data = array();
   $file_list = file($filename);
   for($i=0;$i<count($keyword);$i++) {
       for($j=1;$j<count($file_list);$j++) {
           $file_list_part = explode($SETTING['division1'],$file_list[$j]);
           if( trim($file_list_part[0]) == trim($keyword[$i]) ) {
               $data['ip'][$i] = (int)trim($file_list_part[1]);
               $data['pv'][$i] = (int)trim($file_list_part[2]);
               break;
           } elseif ($j == (count($file_list)-1)) {
               $data['ip'][$i] = "0";
               $data['pv'][$i] = "0";
               break;
           }
       }
   }
   return $data;
}

// Read the key to array
function read_keyarray($filename,$list)
{
   global $SETTING;

   $str = "<?php exit(\"".$SETTING['cannotview']."\");?>\n";
   if(!file_exists($filename)) { write_file($filename,$str); }

   $array = array();
   $file_list = file($filename);
   for($i=1;$i<count($file_list);$i++) {
       $file_list_part = explode($SETTING['division1'],$file_list[$i]);
       if(count($file_list_part) == $list) {
           $array[] = trim($file_list_part[0]);
       }
   }
   return $array;
}

// The sum of all
function read_sum($filename,$keyword)
{
   global $SETTING;

   $str = "<?php exit(\"".$SETTING['cannotview']."\");?>\n";
   if(!file_exists($filename)) { write_file($filename,$str); }

   $data = array();
   $file_list = file($filename);
   for($i=0;$i<count($keyword);$i++) {
       for($j=1;$j<count($file_list);$j++) {
           $file_list_part = explode($SETTING['division1'],$file_list[$j]);
           if( trim($file_list_part[0]) == trim($keyword[$i]) ) {
             $data['ip'] += $file_list_part[1];
             $data['pv'] += $file_list_part[2];
             break;
           }
       }
   }
   $data['ip'] = (($data['ip'] == 0) ? "1" : $data['ip']);// Dividend can't be 0
   $data['pv'] = (($data['pv'] == 0) ? "1" : $data['pv']);// Dividend can't be 0
   return $data;
}

// The max of all
function read_max($filename,$keyword)
{
   global $SETTING;

   $str = "<?php exit(\"".$SETTING['cannotview']."\");?>\n";
   if(!file_exists($filename)) { write_file($filename,$str); }

   $data = array();
   $file_list = file($filename);
   for($i=0;$i<count($keyword);$i++) {
       for($j=1;$j<count($file_list);$j++) {
           $file_list_part = explode($SETTING['division1'],$file_list[$j]);
           if( trim($file_list_part[0]) == trim($keyword[$i]) ) {
             $data['ip'] = ((int)$data['ip'] < (int)$file_list_part[1]) ? trim($file_list_part[1]) : $data['ip'];
             $data['pv'] = ((int)$data['pv'] < (int)$file_list_part[2]) ? trim($file_list_part[2]) : $data['pv'];
             break;
           }
       }
   }
   $data['ip'] = (($data['ip'] == 0) ? "1" : $data['ip']);// Dividend can't be 0
   $data['pv'] = (($data['pv'] == 0) ? "1" : $data['pv']);// Dividend can't be 0
   return $data;
}

// How many record
function read_number($filename,$list)
{
   global $SETTING;

   $str = "<?php exit(\"".$SETTING['cannotview']."\");?>\n";
   if(!file_exists($filename)) { write_file($filename,$str); }

   $number = 0;
   $file_list = file($filename);
   for($i=1;$i<count($file_list);$i++) {
       $file_list_part = explode($SETTING['division1'],$file_list[$i]);
       if(count($file_list_part) == $list) {
           $number++;
       }
   }
   return $number;
}

//////

// Pagination
function pagination($url,$total,$perpage=10,$list=7)
{
   global $_GET,$LANGUAGE;

   $page       = (empty($_GET['page']) || $_GET['page'] <= 0) ? 1 : (int)$_GET['page'];
   $page_total = ceil($total/$perpage); 
   $page_total = (empty($page_total) || $page_total <= 0) ? 1 : (int)$page_total;
   $list_first = $page - floor($list/2);
   $list_first = (empty($list_first) || $list_first <= 0) ? 1 : (int)$list_first;

   if( $page <= 0 || $page > $page_total) {
       $back = $_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : ($url."page=1");
       echo "<script language='JavaScript'>alert('".$LANGUAGE['page_nopage']."');document.location.href='".$back."';</script>";
       echo $LANGUAGE['page_nopage']."<meta http-equiv='refresh' content='0;URL=".$back."'>";
   }

   echo "<span class='pagelink_side' title='Current page:".$page."/Total page:".$page_total."'><font color=#FF0000>".$page."</font>/".$page_total."</span>";

   if($list_first>1) {
       echo " <span class='pagelink_side' title='".$LANGUAGE['page_gofirst']."'><a href='".$url."page=1' target='_self'>&laquo;</a></span>";
   }
   if($page>1) {
       echo " <span class='pagelink_side' title='".$LANGUAGE['page_prepage']."'><a href='".$url."page=".($page-1)."' target='_self'>&#8249;</a></span>";
   }
   for($i=0;$i<$list;$i++) {
       if($list_first+$i>0 && $list_first+$i<=$page_total) {
          if($page == $list_first+$i) {
             echo " <span class='pagelink_current' title='".$LANGUAGE['page_currentpage']." ".($list_first+$i)."'><font color=#FF0000>".($list_first+$i)."</font></span>";
          }else{
             echo " <span class='pagelink' title='".$LANGUAGE['page_page']." ".($list_first+$i)."'><a href='".$url."page=".($list_first+$i)."' target='_self'>".($list_first+$i)."</a></span>";
          }
       }
   }
   if($page_total>$page) {
       echo " <span class='pagelink_side' title='".$LANGUAGE['page_nextpage']."'><a href='".$url."page=".($page+1)."' target='_self'>&#8250;</a></span>";
   }
   if($page_total>($list_first+$list-1)) {
       echo " <span class='pagelink_side' title='".$LANGUAGE['page_golast']."'><a href='".$url."page=".$page_total."' target='_self'>&raquo;</a></span>";
   }

   echo " <select onchange='top.location.href=this.options[this.selectedIndex].value' class='select'>";
   for($i = 1; $i <= $page_total; $i++) {
       $selected = ($page == $i) ? "selected" : "";
       echo "<option value='".$url."page=".$i."' ".$selected.">".$i."</option>";
   }
   echo "</select>";

   return TRUE;
}

// Debug of print var
function fp($var,$type="")
{
    $print = ($type != "") ? "var_dump" : "print_r";
    echo "<pre>";
    $print($var);
    echo "<pre>";
}
?>
